package com.example.canal.conf;

import com.example.canal.event.TableInfo;
import com.example.canal.service.EventHandlerFactory;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 事件处理 工厂
 * 配置注入
 *
 * @author maowei
 * @date 2020/9/7
 * @time 17:13
 */
@Configuration
public class EventHandlerFactoryConfig {



    @Autowired
    private CanalConfig canalConfig;

    @Bean
    public EventHandlerFactory register() {
        EventHandlerFactory eventHandlerFactory = new EventHandlerFactory();
        //是否是自定义表处理
        Boolean custom = canalConfig.getCustom();
        if (custom) {
            //多过滤器分隔
            if (StringUtils.isBlank(canalConfig.getFilter())) {
                return eventHandlerFactory;
            }
            String[] filterSplit = canalConfig.getFilter().split(CanalConstants.DEFAULT_FILTER_SPLIT);
            List<String> filterList = Arrays.asList(filterSplit);
            //表信息
            List<TableInfo> tableInfoList = new ArrayList<>(filterList.size());
            for (String filter : filterList) {
                String[] split = filter.split(CanalConstants.DEFAULT_TABLE_SPLIT);
                if (split.length > 1) {
                    tableInfoList.add(new TableInfo(split[0], split[1]));
                } else {
                    throw new RuntimeException("filter格式解析发生错误");
                }
            }
            //给每个数据库的不同表添加业务处理逻辑
            for (TableInfo tableInfo : tableInfoList) {
                //可以使用if判断, 不同表添加不同的逻辑
            }
        }
        return eventHandlerFactory;
    }


}
